package com.qihang.librarymanage.jframe.user;

import com.qihang.librarymanage.utils.Theme;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class BookSearch extends JFrame {
    
    private JPanel contentPane;
    private JTextField searchField;
    private JTable bookTable;
    private JButton searchButton;
    private JButton backButton;
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;
    
    /**
     * 创建图书搜索界面
     */
    public BookSearch() {
        setTitle("图书搜索系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1000, 600);
        setLocationRelativeTo(null);
        
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));
        
        // 创建顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setPreferredSize(new Dimension(getWidth(), 80));
        topPanel.setBackground(new Color(240, 240, 240));
        contentPane.add(topPanel, BorderLayout.NORTH);
        topPanel.setLayout(null);
        
        // 添加返回按钮
        backButton = new JButton("返回");
        backButton.setBounds(20, 20, 80, 40);
        backButton.setFont(new Font("宋体", Font.BOLD, 14));
        backButton.setBackground(new Color(220, 220, 220));
        backButton.setFocusPainted(false);
        backButton.setFocusable(false); // 设置为不可聚焦
        backButton.setDefaultCapable(false); // 设置为非默认按钮
        topPanel.add(backButton);
        
        // 添加返回按钮点击事件
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭当前窗口
                // 跳转到BookInfo界面
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        new BookInfo();
                    }
                });
            }
        });
        
        // 添加笑脸图标和提示文字
        JLabel tipLabel = new JLabel("😊 请输入书籍名称：");
        tipLabel.setFont(new Font("宋体", Font.BOLD, 16));
        tipLabel.setBounds(120, 20, 200, 40);
        topPanel.add(tipLabel);
        
        // 添加搜索框
        searchField = new JTextField();
        searchField.setBounds(320, 20, 510, 40);
        searchField.setFont(new Font("宋体", Font.PLAIN, 14));
        topPanel.add(searchField);
        
        // 添加搜索按钮
        searchButton = new JButton("搜索");
        searchButton.setBounds(850, 20, 100, 40);
        searchButton.setFont(new Font("宋体", Font.BOLD, 14));
        searchButton.setBackground(new Color(135, 206, 250));
        searchButton.setForeground(Color.WHITE);
        getRootPane().setDefaultButton(searchButton); // 设置搜索按钮为默认按钮
        topPanel.add(searchButton);
        
        // 创建表格说明标签
        JPanel tableHeaderPanel = new JPanel();
        tableHeaderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());
        contentPane.add(centerPanel, BorderLayout.CENTER);
        
        JLabel tableInfoLabel = new JLabel("🔍 点击下方对应的表格内容即可跳转");
        tableInfoLabel.setFont(new Font("宋体", Font.PLAIN, 14));
        tableHeaderPanel.add(tableInfoLabel);
        centerPanel.add(tableHeaderPanel, BorderLayout.NORTH);
        
        // 创建表格
        String[] columns = {"图书名称", "图书作者", "图书价格", "图书类型", "图书简介"};
        model = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        
        // 添加示例数据
        addSampleData();
        
        bookTable = new JTable(model);
        bookTable.setRowHeight(30);
        bookTable.setFont(new Font("宋体", Font.PLAIN, 14));
        bookTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14));
        bookTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        
        // 设置排序器
        sorter = new TableRowSorter<>(model);
        bookTable.setRowSorter(sorter);
        
        // 设置列宽
        bookTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        bookTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        bookTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        bookTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        bookTable.getColumnModel().getColumn(4).setPreferredWidth(450);
        
        // 设置除图书简介外的其他列居中显示
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        
        for (int i = 0; i < bookTable.getColumnCount(); i++) {
            if (i != 4) { // 除了图书简介列(索引4)之外都居中
                bookTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
            }
        }
        
        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(bookTable);
        centerPanel.add(scrollPane, BorderLayout.CENTER);
        
        // 添加搜索按钮点击事件
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });
        
        // 添加回车键搜索功能
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });
    }
    
    /**
     * 添加示例数据
     */
    private void addSampleData() {
        model.addRow(new Object[]{"雪中悍刀行", "烽火戏诸侯", "220.0", "悬疑科幻", "有个白狐儿脸，佩双刀绣..."});
        model.addRow(new Object[]{"都市风水师", "许叶", "89.0", "悬疑科幻", "《都市风水师》是许叶写的..."});
        model.addRow(new Object[]{"五年高考三年模拟", "首都师范大学出版社", "300.0", "青春校园", "当你的生命还剩下八年..."});
        model.addRow(new Object[]{"水浒传", "施耐庵", "60.0", "经典著作", "《水浒传》是以白话文写..."});
        model.addRow(new Object[]{"骆驼祥子", "老舍", "100.0", "经典著作", "《骆驼祥子》讲述的是中..."});
        model.addRow(new Object[]{"状元笔记", "上海科技出版社", "100.0", "青春校园", "《状元笔记》丛书：问鼎..."});
        model.addRow(new Object[]{"李清照词集", "江苏出版社", "89.0", "经典著作", "李清照（1084年3月13日—..."});
        model.addRow(new Object[]{"羊脂球", "莫泊桑", "210.0", "青春校园", "《羊脂球》是一部由法国..."});
        model.addRow(new Object[]{"人间喜剧", "巴尔扎特", "200.0", "青春校园", "《人间喜剧》展示了法国..."});
        model.addRow(new Object[]{"红与黑", "司汤达", "89.0", "经典著作", "《红与黑》是一部由19世..."});
        model.addRow(new Object[]{"堂吉诃德", "塞万提斯", "67.0", "经典著作", "《唐·吉诃德》（又译作..."});
    }
    
    /**
     * 执行搜索功能
     */
    private void performSearch() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            // 如果搜索框为空，显示所有数据
            sorter.setRowFilter(null);
            return;
        }
        
        // 创建过滤器列表，用于多列搜索
        List<RowFilter<Object, Object>> filters = new ArrayList<>();
        
        // 对所有列进行搜索
        for (int i = 0; i < model.getColumnCount(); i++) {
            filters.add(RowFilter.regexFilter("(?i)" + Pattern.quote(keyword), i));
        }
        
        // 使用OR组合过滤器，任何一列包含关键词即显示
        RowFilter<Object, Object> combinedFilter = RowFilter.orFilter(filters);
        sorter.setRowFilter(combinedFilter);
        
        // 显示搜索结果数量
        int resultCount = bookTable.getRowCount();
        if (resultCount == 0) {
            JOptionPane.showMessageDialog(this, "没有找到匹配的图书", "搜索结果", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "找到 " + resultCount + " 本匹配的图书", "搜索结果", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    /**
     * 启动应用
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    // 应用主题1
                    new Theme(1);
                    BookSearch frame = new BookSearch();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
